package gw.com.android.utils;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import com.gwtsz.android.rxbus.RxBus;

import java.util.Timer;
import java.util.TimerTask;

import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.account.LoginActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.view.BtnClickListener;


/**
 * 断网，断开服务器的一些逻辑处理类
 * 
 * @author Administrator
 * 
 */
public class ServerConnnectUtil {
	
	/**重连提示定时器相关参数*/
	private final Timer timer = new Timer();
	private TimerTask task;
	/**行情自动重连次数*/
	public int autoQuoteConnect = 0;
	/**交易自动重连次数*/
	public int autoTradeConnect = 0;
	/**判断是否正在重连*/
	public boolean isReconnect = false;
	/**行情服务器连接状态，true标识连接，false标识断开*/
	public boolean isQuoteConnect = false;
	/**交易服务器连接状态，true标识连接，false标识断开*/
	public boolean isTradeConnect = false;
	/**判断应用是否在后台运行，true标识在后台，false标识在前台*/
	public boolean isBackRuning = false;
	/**标识网络是否是连接状态，true标识连接，false标识失败*/
	public boolean isNetConnect = true;

	/**
	 * 当前类对象
	 */
	public static ServerConnnectUtil mInstance;
	
	/**
	 * 返回当前类对象
	 * @return
	 */
	public static ServerConnnectUtil instance(){
		if(null == mInstance){
			mInstance = new ServerConnnectUtil();
		}
		return mInstance;
	}
	
	/**
	 * 初始化定时任务
	 */
	public void initTimerTask(){
		if(isBackRuning || isReconnect || !isNetConnect || (ServerConnnectUtil.instance().isTradeConnect && ServerConnnectUtil.instance().isQuoteConnect)){
			return;
		}
		showLoading();
		// 初始化定时器
		task = new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(AppContances.HANDLER_TIME_OUT);
			}
		};
		// 启动定时器,10S后如果没有响应,则提示超时信息
		timer.schedule(task, AppContances.TIMER_LOADING_TASK_TIME);
		isReconnect = true;
	}
	
	/**
	 * 取消定时器
	 */
	public void cancelTask(boolean isSuccess){
		isReconnect = false;
        hideLoading();
		if(task != null){
			task.cancel();
			task = null;
		}
	}

	/**
	 * 显示加载圈
	 */
	private void showLoading() {
		Logger.e("显示重连加载圈。。。。。。");
		RxBus.getInstance().post(GTSConst.REPLY_STATUS_PROGRESS,true);
		connnectFailToast(ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1056));
	}

	/**
	 * 隐藏加载圈
	 */
	public void hideLoading() {
		Logger.e("重连加载圈消失！！！");
		RxBus.getInstance().post(GTSConst.REPLY_STATUS_PROGRESS,false);
	}

	/**
	 * 行情状态
	 * @param isConnect
     */
	public void setQuoteState(boolean isConnect){
		if(isConnect){
			isQuoteConnect = true;
			autoQuoteConnect = 0;
		}else{
			isQuoteConnect = false;
		}
	}

	/**
	 * 交易状态
	 * @param isConnect
     */
	public void setTradeState(boolean isConnect){
		if(isConnect){
			isTradeConnect = true;
			autoTradeConnect = 0;
		}else{
			isTradeConnect = false;
		}
	}

	/**
	 * 显示加载圈
	 * @param type
     */
	public void showProgress(int type){
		int connectNumber = 1;
		if(type == AppContances.SERVER_TYPE_QUOTE){
			autoQuoteConnect ++;
			connectNumber = autoQuoteConnect;
		}else if(type == AppContances.SERVER_TYPE_TRADE){
			autoTradeConnect ++;
			connectNumber = autoTradeConnect;
		}
		if(!isBackRuning && connectNumber == 1){
			Logger.e("onServerResponse 服务器重连状态 iNotification = " + type + ", " + connectNumber);
			BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
			if(!(mOwnerAct instanceof LoginActivity) && GTConfig.instance().hasShowMain){
				initTimerTask();
			}
		}
	}
	/**
	 * 处理异常连接失败
	 * @param  errorShowMsg        提示的错误信息
	 */
	public void connnectFailToast(final String errorShowMsg){
		final BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
		if(null != mOwnerAct && !mOwnerAct.isFinishing()){

			mOwnerAct.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mOwnerAct.showToastPopWindow(errorShowMsg);
				}
			});
		}
	}
	
	/**
	 * 处理连接超时，断网提示
	 * @param  errorShowMsg        提示的错误信息
	 */
	public void connnectTimeOutToast(final int errorShowMsg){
		final BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
		if(null != mOwnerAct && !mOwnerAct.isFinishing() && mOwnerAct.isResumed){

			mOwnerAct.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mOwnerAct.showToastPopWindow(AppMain.getAppString(errorShowMsg));
				}
			});
		}
	}

	/**
	 * 处理连接超时，断网提示
	 * @param  errorShowMsg        提示的错误信息
	 */
	public void connnectTimeOutToast(final String errorShowMsg){
		final BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
		if(null != mOwnerAct && !mOwnerAct.isFinishing() && mOwnerAct.isResumed){

			mOwnerAct.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mOwnerAct.showToastPopWindow(errorShowMsg);
				}
			});
		}
	}

	public Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == AppContances.HANDLER_TIME_OUT){
				Activity activity = AppActivities.getSingleton().currentActivity();
				if(null != activity && !activity.isFinishing()){
					cancelTask(false);
				}
			}
		}
	};

	/**
	 * 判断并发起重连，需弹层提示
	 * @param act
     */
	public void reConnectServerConfirm(Activity act){
		// 先判断交易服务器和行情服务器是否连接成功
		final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(act, "",
				ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1009));
		dialog.setBtnClickListener(new BtnClickListener() {

			@Override
			public void onBtnClick(int viewID) {
				hasReConnectServer();
			}
		});
		dialog.show();
	}

	/**
	 * 判断并发起重连，不需要弹层提示，true标识要重连，false标识不要重连
	 */
	public boolean hasReConnectServer(){
		if(!isBackRuning){
			if (!isTradeConnect && !isQuoteConnect) {
				AppTerminal.instance().setReConnect(AppContances.SERVER_TYPE_BOTH);
				return true;
			}else if(!isTradeConnect) {
				AppTerminal.instance().setReConnect(AppContances.SERVER_TYPE_TRADE);
				return true;
			}else if(!isQuoteConnect){
				AppTerminal.instance().setReConnect(AppContances.SERVER_TYPE_QUOTE);
				return true;
			}

		}

		return false;
	}

	/**
	 * 判断连接行情服务器
	 * @return
     */
	public boolean hasReConnectQuote(){
		if(!isQuoteConnect){
			AppTerminal.instance().setReConnect(AppContances.SERVER_TYPE_QUOTE);
			return true;
		}

		return false;
	}

	/**
	 * 判断连接交易服务器
	 * @return
     */
	public boolean hasReConnectTrade(){
		if(!isTradeConnect){
			AppTerminal.instance().setReConnect(AppContances.SERVER_TYPE_TRADE);
			return true;
		}

		return false;
	}

    /**应用退到后台的一些操作和处理*/
	private final Timer disConnectTimer = new Timer();
	private TimerTask disConnectTask;

	/**
	 * 应用退到后台，断开服务器
	 */
	public void disConnectServer(){
        if(isBackRuning){
			// 初始化定时器
			if (null != disConnectTask){
				return;
			}
			disConnectTask = new TimerTask() {
				@Override
				public void run() {
					AppTerminal.instance().onDisconnect(AppContances.SERVER_TYPE_BOTH);
				}
			};
			// 启动定时器,1分钟后如果没有响应,则断开服务器连接
			disConnectTimer.schedule(disConnectTask, AppContances.TIMER_DISCONNECT_TASK_TIME);
		}
	}

	/**
	 * 取消定时器
	 */
	public void cancelDisConnectTask(){
		if(disConnectTask != null){
			disConnectTask.cancel();
			disConnectTask = null;
		}
	}

    public boolean isQuoteConnect() {
        return isQuoteConnect;
    }
}
